package org.tim.listener;

import lombok.var;
import org.tim.spi.ModuleLifecycle;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioListener;

import java.util.Iterator;
import java.util.ServiceLoader;

public class ServerAioListenerHandler implements ServerAioListener {
    @Override
    public boolean onHeartbeatTimeout(ChannelContext channelContext, Long aLong, int i) {
        return false;
    }

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean b, boolean b1) throws Exception {
        var listener = getModuleLifecycleAspects();
        while (listener.hasNext()) {
            var next = listener.next();
            next.onAfterConnected(channelContext, b, b1);
        }
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int i) throws Exception {
        var listener = getModuleLifecycleAspects();
        while (listener.hasNext()) {
            var next = listener.next();
            next.onAfterDecoded(channelContext, packet, i);
        }
    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int i) throws Exception {
        var listener = getModuleLifecycleAspects();
        while (listener.hasNext()) {
            var next = listener.next();
            next.onAfterReceivedBytes(channelContext, i);
        }
    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean b) throws Exception {
        var listener = getModuleLifecycleAspects();
        while (listener.hasNext()) {
            var next = listener.next();
            next.onAfterSent(channelContext, packet, b);
        }
    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long l) throws Exception {
        var listener = getModuleLifecycleAspects();
        while (listener.hasNext()) {
            var next = listener.next();
            next.onAfterHandled(channelContext, packet, l);
        }
    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String s, boolean b) throws Exception {
        var listener = getModuleLifecycleAspects();
        while (listener.hasNext()) {
            var next = listener.next();
            next.onBeforeClose(channelContext, throwable, s, b);
        }
    }

    private Iterator<ModuleLifecycle> getModuleLifecycleAspects(){
        ServiceLoader<ModuleLifecycle> moduleLifecycles = ServiceLoader.load(ModuleLifecycle.class);
        return moduleLifecycles.iterator();
    }
}
